var express = require("express");
var router = express.Router();

const { couponModule,propModule } = require('../module/module');
const multer = require('multer'); // 添加 multer 引入
const path = require('path'); // 添加 path 引入


const { hotModel, appreciateModel, newListModel } = require("../module/module");

/* GET home page. */
router.get("/", function (req, res, next) {
  res.render("目录", { title: "好久不见" });
});
// 获取热销列表
router.get("/getHotList", async (req, res) => {
  try {
    const data = await hotModel.find();
    res.send(data);
  } catch (err) {
    console.log(err);
  }
});
// 获取热销列表单个商品
router.get("/getHostListByOne/:id", async (req, res) => {
  try {
    const productId = req.params.id;
    const product = await hotModel.findById(productId);
    if (!product) {
      return res.status(404).send({ msg: "商品不存在" });
    }
    res.send(product);
  } catch (err) {
    console.log(err);
  }
});
// 获取一番赏列表
router.get("/getAppreciateList", async (req, res) => {
  try {
    const data = await appreciateModel.find();
    res.send(data);
  } catch (err) {
    console.log(err);
  }
});
// 获取新品专区列表
router.get("/getNewList", async (req, res) => {
  try {
    const data = await newListModel.find();
    res.send(data);
  } catch (err) {
    console.log(err);
  }
});




const storage = multer.diskStorage({
  destination: function (req, file, cb) {
    cb(null, "uploads/");
  },
  filename: function (req, file, cb) {
    cb(null, Date.now() + path.extname(file.originalname));
  },
});

const upload = multer({ storage: storage });

router.use(express.json());
router.use(express.urlencoded({ extended: true }));

// 提供静态文件服务
router.use("/uploads", express.static("uploads"));

// 上传头像的 API
router.post("/api/upload-avatar", upload.single("avatar"), async (req, res) => {
  const { userID } = req.body;
  const img = `/uploads/${req.file.filename}`;

  // 假设你有某种方式识别当前用户，这里是通过 userID
  const user = await nameScheam.findById(userID); // 确保你按照实际情况引入模型
  if (user) {
    user.img = img;
    await user.save();
    res.json({ success: true, imgPath: img });
  } else {
    res.status(404).json({ success: false, message: "User not found" });
  }
});

router.get("/coupon", async function (req, res, next) {
  try {
    const data = await couponModule.find({});
    res.send({
      code: 200,
      msg: "展示数据",
      data: data,
    });
  } catch (err) {
    res.send(err);
  }
});

router.get("/prop", async function (req, res, next) {
  try {
    const data = await propModule.find({});
    res.send({
      code: 200,
      msg: "展示数据",
      data: data,
    });
  } catch (err) {
    res.send(err);
  }
});

module.exports = router;
